package com.syg.rabbitmq.consumer;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;
import java.util.concurrent.TimeoutException;


/**
 * 消费者的代码是一样的,只需要在使用消费的时候指定队列即可
 */
public class Publish_Subscribe_Consumer2 {

    public static void main(String[] args) throws IOException, TimeoutException {
        // 1,创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();

        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");

        // 3,创建连接
        Connection connection = factory.newConnection();
        // 4,创建Channel
        Channel channel = connection.createChannel();


        Consumer consumer = new DefaultConsumer(channel) {
            /*
             * 回调方法，当收到消息后，会自动执行该方法
             * 1，consumerTag :标识
             * 2，Envelope 获取交换机、路由等信息
             * */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("数据库=" + new String(body));
            }
        };

        // 消费的时候指定队列名,保证不会消费到其他队列中的消息
        // autoAck 为false,消费者启动时会再次消费之前的数据(可能是使用方式不对)
        channel.basicConsume("queueFanout2", true, consumer);

    }
}
